import { useEffect, useState } from 'react'
import { Modal, Radio, Form, Input, Row, Col, Checkbox, Button, message } from 'antd'
import styles from '../css/LoginForm.module.css'
import { getCaptcha, userIsExist, addUser, userLogin, getUserById } from '../api/user.js'
import { useDispatch } from 'react-redux'
import { initUserInfo, changeLoginStatus } from '../redux/userSlice.js'
export default function LoginForm(props) {
  const dispatch = useDispatch()
  const [captcha, setCaptcha] = useState(null)
  // 数据初始化
  const captchaClickHandle = async () => {
    const result = await getCaptcha()
    setCaptcha(result)
  }
  // 初始化
  useEffect(() => {
    captchaClickHandle()
  }, [props.isModalOpen])
  const handleOk = () => {}
  const [value, setValue] = useState(1)
  // 按钮切换
  const onChange = (e) => {
    setValue(e.target.value)
    // 切换按钮重置验证码
    captchaClickHandle()
  }
  // 登录表单的状态数据
  const [loginInfo, setLoginInfo] = useState({
    loginId: '',
    loginPwd: '',
    captcha: '',
    remember: false,
  })

  // 登录
  const loginHandle = async (e) => {
    console.log(e)
    const res = await userLogin(loginInfo)
    if (res.data) {
      // 验证码是正确的
      // 接下来会有这么几种情况 （1）密码不正确 （2）账户被冻结 （3）账户正常，能够正常登录
      const data = res.data
      if (!data.data) {
        // 账号密码不正确
        messageApi.error('账号或密码不正确')
        captchaClickHandle()
      } else if (!data.data.enabled) {
        // 账号被禁用了
        messageApi.warning('账号被禁用')
        captchaClickHandle()
      } else {
        // 登录成功
        // 存储token
        localStorage.setItem('userToken', data.token)
        const res = await getUserById(data.data._id)
        // 还需要将用户的信息存储到数据仓库里面
        dispatch(initUserInfo(res.data))
        // 将数据仓库的登录状态进行修改
        dispatch(changeLoginStatus(true))
        // 关闭登录注册的弹出框
        clearInfo()
      }
    } else {
      // 如果data为空 出错了
      messageApi.error(res.msg)
      captchaClickHandle()
    }
  }
  /**
   * @param {*} oldInfo 之前整体的状态
   * @param {*} newContent 用户输入的新的内容
   * @param {*} key 对应的键名
   * @param {*} setInfo 修改状态值的函数
   */
  const updateInfo = (oldInfo, newContent, key, setInfo) => {
    const oldVal = { ...oldInfo }
    oldVal[key] = newContent
    setInfo(oldVal)
  }

  // 注册表单的状态数据
  const [registerInfo, setRegisterInfo] = useState({
    loginId: '',
    nickname: '',
    captcha: '',
  })
  const [messageApi, contextHolder] = message.useMessage()
  // 效验规则
  const checkLoginIdIsExist = async () => {
    if (registerInfo.loginId) {
      const { data } = await userIsExist(registerInfo.loginId)
      if (data) {
        messageApi.info('该用户已经注册过了')
      }
    }
  }
  // 注册事件
  const registerHandle = async () => {
    const res = await addUser(registerInfo)
    // console.log(res)
    if (res.data) {
      messageApi.success('用户注册成功，默认密码为 123456')
      // 还需要将用户的信息存储到数据仓库里面
      dispatch(initUserInfo(res.data))
      // 将数据仓库的登录状态进行修改
      dispatch(changeLoginStatus(true))
      // 关闭登录注册的弹出框
      clearInfo()
    } else {
      messageApi.info(res.msg)
      captchaClickHandle()
    }
  }
  // 清空数据事件
  const clearInfo = () => {
    setRegisterInfo({
      loginId: '',
      nickname: '',
      captcha: '',
    })
    setLoginInfo({
      loginId: '',
      loginPwd: '',
      captcha: '',
      remember: false,
    })
    // 关闭弹窗
    props.isModalClose()
  }
  // 重置
  const onReset = () => {
    form.resetFields()
    setRegisterInfo({
      loginId: '',
      nickname: '',
      captcha: '',
    })
    setLoginInfo({
      loginId: '',
      loginPwd: '',
      captcha: '',
      remember: false,
    })
  }
  // 切换样式
  let container = null
  const [form] = Form.useForm()
  if (value === 1) {
    // 登录面板的 JSX
    container = (
      <div className={styles.container}>
        <Form name="basic1" autoComplete="off" onFinish={loginHandle} form={form}>
          <Form.Item
            label="登录账号"
            name="loginId"
            rules={[
              {
                required: true,
                message: '请输入账号',
              },
            ]}
          >
            <Input placeholder="请输入你的登录账号" value={loginInfo.loginId} onChange={(e) => updateInfo(loginInfo, e.target.value, 'loginId', setLoginInfo)} />
          </Form.Item>

          <Form.Item
            label="登录密码"
            name="loginPwd"
            rules={[
              {
                required: true,
                message: '请输入密码',
              },
            ]}
          >
            <Input.Password placeholder="请输入你的登录密码，新用户默认为123456" value={loginInfo.loginPwd} onChange={(e) => updateInfo(loginInfo, e.target.value, 'loginPwd', setLoginInfo)} />
          </Form.Item>

          {/* 验证码 */}
          <Form.Item
            name="logincaptcha"
            label="验证码"
            rules={[
              {
                required: true,
                message: '请输入验证码',
              },
            ]}
          >
            <Row align="middle">
              <Col span={16}>
                <Input placeholder="请输入验证码" value={loginInfo.captcha} onChange={(e) => updateInfo(loginInfo, e.target.value, 'captcha', setLoginInfo)} />
              </Col>
              <Col span={6}>
                <div className={styles.captchaImg} onClick={captchaClickHandle} dangerouslySetInnerHTML={{ __html: captcha }}></div>
              </Col>
            </Row>
          </Form.Item>

          <Form.Item
            name="remember"
            wrapperCol={{
              offset: 5,
              span: 16,
            }}
          >
            <Checkbox onChange={(e) => updateInfo(loginInfo, e.target.checked, 'remember', setLoginInfo)} checked={loginInfo.remember}>
              记住我
            </Checkbox>
          </Form.Item>

          <Form.Item
            wrapperCol={{
              offset: 5,
              span: 16,
            }}
          >
            <Button type="primary" htmlType="submit" style={{ marginRight: 20 }}>
              登录
            </Button>
            <Button type="primary" htmlType="submit" onClick={onReset}>
              重置
            </Button>
          </Form.Item>
        </Form>
      </div>
    )
  } else {
    // 注册面板的 JSX
    container = (
      <div className={styles.container}>
        <Form name="basic2" autoComplete="off" onFinish={registerHandle}>
          <Form.Item
            label="登录账号"
            name="loginId"
            rules={[
              {
                required: true,
                message: '请输入账号，仅此项为必填项',
              },
              // 验证用户是否已经存在
              { validator: checkLoginIdIsExist },
            ]}
            validateTrigger="onBlur"
          >
            <Input placeholder="请输入账号" value={registerInfo.loginId} onChange={(e) => updateInfo(registerInfo, e.target.value, 'loginId', setRegisterInfo)} />
          </Form.Item>

          <Form.Item label="用户昵称" name="nickname">
            <Input placeholder="请输入昵称，不填写默认为新用户xxx" value={registerInfo.nickname} onChange={(e) => updateInfo(registerInfo, e.target.value, 'nickname', setRegisterInfo)} />
          </Form.Item>

          <Form.Item
            name="registercaptcha"
            label="验证码"
            rules={[
              {
                required: true,
                message: '请输入验证码',
              },
            ]}
          >
            <Row align="middle">
              <Col span={16}>
                <Input placeholder="请输入验证码" value={registerInfo.captcha} onChange={(e) => updateInfo(registerInfo, e.target.value, 'captcha', setRegisterInfo)} />
              </Col>
              <Col span={6}>
                <div className={styles.captchaImg} onClick={captchaClickHandle} dangerouslySetInnerHTML={{ __html: captcha }}></div>
              </Col>
            </Row>
          </Form.Item>

          <Form.Item
            wrapperCol={{
              offset: 5,
              span: 16,
            }}
          >
            <Button type="primary" htmlType="submit" style={{ marginRight: 20 }}>
              注册
            </Button>
            <Button type="primary" htmlType="submit" onClick={onReset}>
              重置
            </Button>
          </Form.Item>
        </Form>
      </div>
    )
  }
  return (
    <Modal title="登录/注册" open={props.isModalOpen} onOk={handleOk} onCancel={props.isModalClose}>
      {contextHolder}
      <Radio.Group value={value} onChange={onChange} className={styles.radioGroup} buttonStyle="solid">
        <Radio.Button value={1} className={styles.radioButton}>
          登录
        </Radio.Button>
        <Radio.Button value={2} className={styles.radioButton}>
          注册
        </Radio.Button>
      </Radio.Group>
      {/* jsx的样式 */}
      {container}
    </Modal>
  )
}
